/**
 * Author shuqi
 * Rev
 * Date: 2019-12-10 16:04
 * <p>
 * Copyright (C) 2019 Seeyon, Inc. All rights reserved.
 * <p>
 * This software is the proprietary information of Seeyon, Inc.
 * Use is subject to license terms.
 * @company seeyon.com
 * @since V5 V8.0
 * @author shuqi
 */
package com.shuqi.tools.actions;

import com.intellij.openapi.project.Project;
import com.shuqi.tools.dto.BuildConfig;
import com.shuqi.tools.dto.Manifest;
import com.shuqi.tools.utils.Constants;
import com.shuqi.tools.utils.HttpUtils;
import com.shuqi.tools.utils.LoggerUtils;
import com.shuqi.tools.utils.NotifyUtils;
import com.shuqi.utils.JSONUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description
 * @date 2019-12-10 16:04
 * @since V5 V8.0
 * @author shuqi
 */
public class M3BuildAction extends AbsBuildAction {
	// ${v5Path}/m3files/${team}/${appId}.zip
	private String targetPathFormat = "%s" + File.separator + "m3files" + File.separator + "%s" + File.separator + "%s.zip";

	@Override
	public Constants.BuildType buildType() {
		return Constants.BuildType.CMP;
	}
	@Override
	protected void afterPack(Manifest mateMap, BuildConfig config, File outZip, Project project) {
		File target = new File(String.format(targetPathFormat, config.getV5RuntimePath(),mateMap.getTeam(),mateMap.getAppId()));
		try {
			FileUtils.copyFile(outZip, target);
		} catch (IOException e) {
			LoggerUtils.error("", e);
		}
		// 发布应用
		if(StringUtils.isBlank(config.getSysPwd())){
			NotifyUtils.error("system账号密码为空，无法进行App热加载!",project);
			return;
		}
		new PublishThread(config.getSysPwd(),project).start();
	}
}


class PublishThread extends Thread{
	String passwd;
	Project project;

	public PublishThread(String passwd, Project project) {
		this.passwd = passwd;
		this.project = project;
	}

	@Override
	public void run() {
		//登录
		try {
			Map<String,Object> params = new HashMap<>();
			params.put("login.timezone","");
			params.put("authorization","");
			params.put("fontSize","");
			params.put("screenWidth","1920");
			params.put("screenHeight","1080");
			params.put("login_username","system");
			params.put("login_validatePwdStrength","1");
			params.put("loginName","system");
			params.put("login_password",passwd);
			HttpUtils.Response loginRs = HttpUtils.post("http://127.0.0.1/seeyon/main.do?method=login", params);
			if(loginRs == null
				|| CollectionUtils.isEmpty(loginRs.getHeaders().get("LoginOK"))
				|| !"ok".equalsIgnoreCase(loginRs.getHeaders().get("LoginOK").get(0))
				|| CollectionUtils.isNotEmpty(loginRs.getHeaders().get("LoginError"))){
				LoggerUtils.info(loginRs.getBody());
				if(loginRs != null){
					LoggerUtils.info("登录失败 : " + loginRs.getBody());
				}else{
					LoggerUtils.info("登录失败 !");
				}
				NotifyUtils.error("登录失败 !",project);
				return;
			}
			List<String> cookes = loginRs.getHeaders().get("Set-Cookie");
			String jsessionId = "";
			for (String cooke : cookes) {
				if (cooke.indexOf("JSESSIONID") > -1) {//正则获取JSESSIONID
					jsessionId = cooke.replaceAll(".*JSESSIONID=([^;]*);.*", "$1");
				}
			}
			LoggerUtils.info("登录成功! jsessionId ：" + jsessionId);



			Map<String,Object> relaodparams = new HashMap<>();
			relaodparams.put("managerMethod","reloadV5Apps");
			relaodparams.put("arguments","[{ \"reset\": 0 }]");
			Map<String, String> headrs = new HashMap<>();
			headrs.put("Cookie","JSESSIONID=" + jsessionId + "; loginPageURL=; login_locale=zh_CN");
			headrs.put("Accept-Language","zh-CN;q=0.9,zh;q=0.8");
			HttpUtils.Response reloadRs = HttpUtils.post("http://127.0.0.1/seeyon/ajax.do?method=ajaxAction&managerName=m3AppNewManager", relaodparams,headrs);


			LoggerUtils.info("relaod app body : " + reloadRs.getBody());
			Map<String,Object> rs = JSONUtils.parseJson(reloadRs.getBody(), Map.class);
			if(!rs.get("resultCode").toString().startsWith("60000")){
				NotifyUtils.error("热部署APP失败 !",project);
				return;
			}
			NotifyUtils.info("热部署APP成功,请重启M3客户端,\r\n" + rs.get("message"),project);
		} catch (Exception e) {
			NotifyUtils.error("热部署APP失败!",project);
			LoggerUtils.error("", e);
		}
	}
}